//
//  HDArchiveViewDetailViewController.swift
//  HuaDaoPeifu
//
//  Created by 刘汉琳 on 16/5/17.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit

class HDArchiveViewDetailViewController: UIViewController,HDArchiveHeaderViewDelegate {

    var archiveModel = HDArchivesModel()
    var detailTableView:UITableView!
    var nameArray = [String]()
    
    var picImageModelArray = [[HDPayoutCaseInitModel]()]
    var imageArray = [[HDUploadImageModel]()]
    var optlogModelArray = [HDPayoutoptLogModel]()
    var casefailModelArray = [HDPayoutCasefailModel]() // 问题列表
    var footView:HDTimeLineView!
    var headerView:HDArchiveHeaderView = HDArchiveHeaderView()
    var loss_noticeStr = String()
    var pdfName = String()
    var uploadTimeStr:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupNavigation()
        nameArray = archiveModel.datatype.components(separatedBy: ",")
        requestDetailData()
        // Do any additional setup after loading the view.
    }
    func setupNavigation() {
        title = "赔付状态"
        let rightItem = UIBarButtonItem(title: "产品详情", style: .plain, target: self, action: #selector(rightItemAction))
        navigationItem.rightBarButtonItem = rightItem
    }
    
    func createTableView(){
        detailTableView = UITableView()
        detailTableView.delegate = self
        detailTableView.dataSource = self
        detailTableView.separatorStyle = .none
        view.addSubview(detailTableView)
        
        headerView.archiveModel = archiveModel
        headerView.delegate = self
        headerView.setupHeaderView()
        detailTableView.tableHeaderView = headerView
        
        footView = HDTimeLineView()
        footView.timeArray = self.optlogModelArray
        footView.uploadTimeStr = uploadTimeStr
        footView.setupTimeLineView()
        detailTableView.tableFooterView = footView
        detailTableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
    func requestDetailData(){
        HDApiManagerHandler.requestArchivesDetail(self.archiveModel, success: { [unowned self](response) in
            print(response)
            if response["status"]?.int32Value == 1{
                let  dict:NSDictionary = response["data"] as! NSDictionary
                self.picGetWith(dict["datatype_list"] as! NSDictionary)
                self.optlogGet(dict)
                self.lossNotice(dict)
                if self.archiveModel.is_dishonor.int32Value == 0 {
                    self.archiveModel.dishonor_introduce = dict["dishonor_introduce"] as! String
                }
                self.uploadTimeStr = Int((dict["updated"] as? String)!)!
                
            }
            self.createTableView()
            self.detailTableView.reloadData()
            }) { (failure) in
                print(failure)
        }
    }
    //获取图片
    func picGetWith(_ dict:NSDictionary){
        if self.picImageModelArray.count > 0 {
            self.picImageModelArray.removeAll()
        }
        if self.imageArray.count > 0{
            self.imageArray.removeAll()
            
        }
        for index in 0 ..< self.nameArray.count{
            let str = self.nameArray[index]
            let dataArr = dict[str] as! NSArray
            let  modelArray = HDPayoutCaseInitModel.parses(dataArr) as! [HDPayoutCaseInitModel]
            self.picImageModelArray.append(modelArray)
            //仅仅为了初始化相同空间的数组，接收从相册或者拍照过来的数据
            let getArray = [HDUploadImageModel]()
            self.imageArray.append(getArray)
        }
        
        for index in 0 ..< self.nameArray.count {
            for numberImage in 0..<self.picImageModelArray[index].count {
                
                let image = HDSaveImage.imageWithMessage(String(describing: self.archiveModel.case_id), dataType: self.nameArray[index], imageCount: numberImage)
                let model = HDUploadImageModel()
                model.image = image as? UIImage
                model.imageStatus = .clear
                self.imageArray[index].append(model)
            }
            
        }
        
        
        
    }
    
    func optlogGet(_ dict:NSDictionary){
        let dataArr = dict["optlog"] as! NSArray
        self.optlogModelArray = HDPayoutoptLogModel.parses(dataArr) as! [HDPayoutoptLogModel]
    }
    
    // 错误信息列表
    func casefailData(_ dict:NSDictionary){
        let dataArr = dict["casefail"] as! NSArray
        self.casefailModelArray = HDPayoutCasefailModel.parses(dataArr) as! [HDPayoutCasefailModel]
        
    }
    
    // 获取预赔案通知书
    func lossNotice(_ dict:NSDictionary){
        loss_noticeStr = dict["loss_notice"] as! String
        if loss_noticeStr.characters.count>0 {
            let lossArray = loss_noticeStr.components(separatedBy: "/")
            pdfName = lossArray.last!
            let filePath = FileManager.default
            let pdfPath =   AppConstant.documentsPath + "/" + pdfName
            print(filePath.fileExists(atPath: pdfPath))
            if !filePath.fileExists(atPath: pdfPath){
                DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: {
                    
                    HDApiManagerHandler.requestDownloadNotice(self.loss_noticeStr)
                    
                })
            }
            
        }
    }

    
    
    func btnClickDelegate() {
        detailTableView.reloadData()
    }
    
    func noticeImageClick() {
        if pdfName.characters.count > 0 {
            let filePath = FileManager.default
            let pdfPath =   AppConstant.documentsPath + "/" + pdfName
            print(filePath.fileExists(atPath: pdfPath))
            if filePath.fileExists(atPath: pdfPath) {
                let document = ReaderDocument.withDocumentFilePath(pdfPath, password: nil)
                if(document != nil){
                    let contr = ReaderViewController.init(readerDocument: document)
                    self.navigationController?.pushViewController(contr!, animated: true)
                    
                }
            }else{
                navigationController?.pushViewController(HDNoticeNUllViewController(), animated: true)
            }
            
        }else{
            navigationController?.pushViewController(HDNoticeNUllViewController(), animated: true)
            
        }
        
        
    }

    
    // MARK: - rightItemAction
    func rightItemAction() {
        let insurance = HDInsuranceViewController()
        insurance.policynoStr = "&policyno=" + self.archiveModel.policyno
        navigationController?.pushViewController(insurance, animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    deinit{
        print("deinit")
    }
    

}

extension HDArchiveViewDetailViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.archiveModel.sourceflag.int32Value == 1 {
            return 0
        }
        return nameArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return  1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellStr = "archiveDetail" + String(indexPath.section) + String(headerView.showBtn.isSelected)

        var cell = tableView.dequeueReusableCell(withIdentifier: cellStr) as? HDArchiveDetailTableViewCell
        if cell == nil {
            cell = HDArchiveDetailTableViewCell(style: UITableViewCellStyle.default,reuseIdentifier: cellStr)
        }

        cell?.delegate = self
        if headerView.showBtn.isSelected {
            let model = HDArchiveDetailModel()
            model.imageArray = self.imageArray[indexPath.section]
            model.nameStr = nameArray[indexPath.section]
            model.pictureArray = picImageModelArray[indexPath.section]
            //model.caseid = String(describing: archiveModel.case_id)
            model.section = indexPath.section
            model.isShow = headerView.showBtn.isSelected
            cell!.detailModel = model
        }
        cell?.selectionStyle = .none
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if headerView.showBtn.isSelected {
            let modelArray = self.picImageModelArray[indexPath.section]
            let numberImage = modelArray.count
            let imageHeightOrWith = Int(AppConstant.screenWidth - 20*5)/4
            
            if numberImage/4 == 0 {
                return CGFloat(imageHeightOrWith + 30)
            }else{
                if numberImage%4 > 0 {
                    return CGFloat((imageHeightOrWith + 30)*(numberImage/4 + 1))
                }
                return CGFloat((imageHeightOrWith + 30)*(numberImage/4)) 
            }
            
        }else{
            return 0
        }
        
    }

}


extension HDArchiveViewDetailViewController:HDArchiveDetailDelegate{
    func showBigImageClickDelegate(_ sender: HDImageBtn) {
        let contr = HDImageBrowserViewController()
        let model = HDUploadDetailImageModel()
        model.currentIndex = sender.selectImageNumber
        model.IndexOfNewImage = self.picImageModelArray[sender.selectIndexPath].count
        model.status = 4
        model.uploadImags = self.picImageModelArray[sender.selectIndexPath]
        contr.imageDetail = model
        
        navigationController?.pushViewController(contr, animated: true)
    }
}
